/**未遂事故的调查计划列表页面 */
<template>
  <div class="app-container">

    <div class="filter-container">
      <el-input v-model="listQuery.faultTitle" placeholder="未遂事故题目" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.userName" placeholder="Team长名字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        新增
      </el-button>
    </div>

    <!-- Note that row-key is necessary to get a correct row order. -->
    <el-table ref="dragTable" v-loading="listLoading" :data="list" row-key="id" border fit highlight-current-row style="width: 100%">

      <el-table-column width="180px" align="center" label="调查计划主键" prop="inquiryId" />

      <el-table-column min-width="300px" label="未遂事故题目">
        <template slot-scope="scope">
          <span v-if="scope.row.faultId!=null" @click="handleDetail(scope.row)">{{ scope.row.faultId.faultTitle }}</span></template>
      </el-table-column>
      <el-table-column width="110px" align="center" label="调查计划开始时间" prop="inquiryStartDate">
        <template slot-scope="scope">
          <span>{{ scope.row.inquiryStartDate }}</span></template>
      </el-table-column>
      <el-table-column width="100px" label="调查计划结束时间" prop="inquiryEndDate">
        <template slot-scope="scope">
          <span>{{ scope.row.inquiryEndDate }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="调查Team长" width="95">
        <template slot-scope="scope">
          <span>{{ scope.row.inquiryTeamerCode.userName }}</span></template>
      </el-table-column>
      <el-table-column align="center" label="调查结果" width="80" prop="inquiryOut" />
      <el-table-column class-name="status-col" label="调查计划状态" width="110">

        <template slot-scope="scope">

          <span v-if="scope.row.inquiryStatus==1">申请中...</span>
          <span v-if="scope.row.inquiryStatus==0">已删除</span>
          <span v-if="scope.row.inquiryStatus==2">已裁决</span>
          <span v-if="scope.row.inquiryStatus==3">已驳回</span>
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="230">
        <template v-if="scope.row.faultSatus==2" slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fechData" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 700px; margin-left:50px;">
        <!-- <el-form-item label="调查计划编号" prop="inquiryId">
          <el-input v-model="temp.inquiryId" />
        </el-form-item> -->
        <!-- <el-form-item label="未遂事故单题目" prop="inquiryId">
          <el-input v-model="temp.faultId.faultTitle" />
        </el-form-item> -->
        <el-form-item label="未遂事故单题目" prop="faultName">
          <el-select v-model="faultTitle" class="filter-item" placeholder="请选择未遂事故题目">
            <el-option v-for="item in faultNameList" :key="item.faultId" :label="item.faultTitle" :value="item.faultId" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="loginTime">
          <el-date-picker v-model="temp.loginTime " type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="调查计划开始时间" prop="inquiryStartDate">
          <el-date-picker v-model="temp.inquiryStartDate" type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="调查计划结束时间" prop="inquiryEndDate">
          <el-date-picker v-model="temp.inquiryEndDate " type="datetime" value-format="yyyy-MM-dd hh:mm:ss" placeholder="请选择日期" />
        </el-form-item>
        <el-form-item label="调查计划结果" prop="inquiryOut">
          <markdown-editor ref="markdownEditor" v-model="temp.inquiryOut" :options="{hideModeSwitch:true,previewStyle:'tab'}" height="300px" />
          <!-- <markdown-editor v-model="temp.inquiryOut" height="300px" /> -->
          <!-- <el-input v-model="temp.inquiryOut " /> -->
        </el-form-item>
        <!-- <el-form-item label="调查计划Team长" prop="inquiryTeamerCode">
          <el-select v-model="inquiryTeameruserName" class="filter-item" placeholder="请选择Team长" prop="inquiryTeamerCode">
            <el-option v-for="item in personlist" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="调查计划填写人" prop="inquiryTeamerCode">

          <el-autocomplete
            v-model="inquiryTeameruserName"
            class="el-input"
            :fetch-suggestions="userSearchAsync"
            placeholder="请输入工号"
            :trigger-on-focus="false"
            @select="handleSelect"
          />
        </el-form-item>

        <el-form-item label="附件上传">
          <ul>
            <div style="margin-left:100px">
              <el-upload
                v-model="file"
                class="upload-demo"
                action="http://localhost:8080/ehs_files/upload"
                :on-change="handleChange"
                :on-success="uploadfile"
              ><el-button size="big" type="primary">点击上传</el-button>

              </el-upload>
            </div>
          </ul>.

        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import MarkdownEditor from '@/components/MarkdownEditor'
import { fetchInquiryList, deleteInquiryList, editInquiry, fetchAllCount, getPersonList, getDeptList, createInquery, getFaultNameList } from '@/api/inquiry'
import Sortable from 'sortablejs'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getuserbyemp } from '@/api/user'

// arr to obj, such as { CN : "China", US : "USA" }

export default {
  name: 'Inquiry',
  components: { Pagination, MarkdownEditor },
  directives: { waves },
  data() {
    return {
      options: [],
      list: null,
      total: 0,
      file: null,
      inquiryTeameruserName: null,
      faultTitle: null,
      faultId: null,
      listLoading: true,
      editList: null,
      inquiryTeamerCode: null,
      userId: '',
      deptId: '',
      // faultUserCode: null,
      // faultTeam: null,
      sortable: null,
      oldList: [],
      newList: [],
      // 参数条件
      listQuery: {
        page: 1,
        limit: 20,
        faultTitle: null,
        userName: null

      },
      personlist: null,
      deptlist: null,
      faultNameList: null,
      temp: {
        inquiryId: undefined,
        loginTime: '',
        inquiryTeamerCode: '',
        inquiryStartDate: '',
        inquiryEndDate: '',
        inquiryStatus: 1,
        inquiryOut: '',
        faultIdNeed: '',
        faultName: ''

      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增',
        detail: '明细'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        loginTime: [{ required: true, message: '登陆时间不能为空', trigger: 'blur' }],
        inquiryStartDate: [{ required: true, message: '调查开始时间不能为空', trigger: 'blur' }],
        inquiryEndDate: [{ required: true, message: '调查结束时间不能为空', trigger: 'blur' }],
        inquiryOut: [{ required: true, message: '调查结果不能为空', trigger: 'blur' }]
        // inquiryTeamerCode: [{ required: true, message: 'inquiryTeamerCode is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.fechData()
  },
  methods: {
    fechData() {
      getPersonList().then(response => {
        this.personlist = response.listName
      })

      getDeptList().then(response => {
        this.deptlist = response.listName
      })
      getFaultNameList().then(response => {
        this.faultNameList = response.listName
        console.log(response.listName)
      })
      fetchAllCount().then(response => {
        this.total = response.count
      })
      fetchInquiryList(this.listQuery).then(response => {
        this.listLoading = true
        this.list = response.ehsinquiryList
        console.log('ceshi shuchu' + this.list)
        this.showList = response.ehsinquiryList
        this.listLoading = false
      })
    },

    handleDownload() {

    },
    showReviewer() {

    },
    resetTemp() {
      this.temp = {
        inquiryId: undefined,
        loginTime: '',
        inquiryTeamerCode: '',
        inquiryStartDate: '',
        inquiryEndDate: '',
        inquiryStatus: 1,
        inquiryOut: '',
        faultIdNeed: '',
        inquiryUser: [],
        inquiryUserAll: '',
        faultName: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      // alert(this.dialogStatus)
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // 问题所在：select选择后不返回数据到选择框
          const userName = this.inquiryTeameruserName
          const faultName1 = this.faultTitle

          // alert('ceshi' + faultName1)
          this.temp.author = 'vue-element-admin'
          const query = { loginTime: this.temp.loginTime, inquiryStartDate: this.temp.inquiryStartDate, inquiryEndDate: this.temp.inquiryEndDate, inquiryOut: this.temp.inquiryOut, userName: userName, faultIdNeed: faultName1, userId: this.userId }
          createInquery(query).then(() => {
            this.list.unshift(this.temp.userName)
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Created Successfully',
              type: 'success',
              duration: 2000
            })
            location.reload()
          })
        }
      })
    },

    async userSearchAsync(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName + '-' + r.userId
        tem_obj.userName = r.userName
        tem_obj.userId = r.userId
        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async userSearchAsync1(queryString, callback) {
      var list = []
      const { userList } = await getuserbyemp(queryString)
      userList.forEach(r => {
        var tem_obj = {}
        tem_obj.value = r.empNo + '-' + r.userName + '-' + r.userId
        tem_obj.userName = r.userName
        tem_obj.userId = r.userId
        list.push(tem_obj)
      })

      callback(list)
      // console.log(queryString)
    },
    async handleSelect(u) {
      this.inquiryTeameruserName = u.userName
      this.userId = u.userId
      // console.log(this.userId)
    },

    handleFilter() {
      this.listQuery.page = 1

      this.fechData()
    },
    handleDelete(row) {
      // alert(row.inquiryId)
      deleteInquiryList(row.inquiryId).then(response => {
        console.log('success')
        // alert('success')
      })
      this.fechData()
    },

    handleEdit(row) {
      getPersonList().then(response => {
        // console.log('666666' + response)
        this.personlist = response.listName
        // alert('999')
      })
      getDeptList().then(response => {
        this.deptlist = response.listName
      })

      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1) // copy obj
      this.inquiryTeameruserName = this.temp.inquiryTeamerCode.userName
      this.faultTitle = this.temp.faultId.faultTitle
      this.faultIdNeed = this.temp.faultId.faultId
      // alert(this.faultId)
      this.inquiryOut = this.temp.inquiryOut
      this.temp.timestamp = new Date(this.temp.timestamp)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      // alert(this.dialogStatus)
      if (this.dialogStatus === 'detail') {
        location.reload()
      } else if (this.dialogStatus === 'update') {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            // alert('进入')
            const tempData = Object.assign({}, this.temp)
            const query1 = JSON.parse(JSON.stringify(tempData))
            // alert('XXXXXXXXXXXXXXXXXX' + this.faultIdNeed)
            console.log('XXXXXXXXXXXXXXXXXX' + this.faultId)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            const query = { inquiryId: query1.inquiryId, faultId1: this.faultIdNeed, inquiryOut: query1.inquiryOut, userName: this.inquiryTeameruserName }
            editInquiry(query).then(response => {
              // this.obj = response
              this.inquiryId = response.ehsinquiry.inquiryId
              this.inquiryOut = response.ehsinquiry.inquiryOut
              // console.log('修改后' + response)
              // alert('修改成功')
            })
            // 刷新页面
            location.reload()
          }
        })
      }
    },
    handleDetail(row) {
      // alert(row)
      console.log(row)

      const row1 = JSON.parse(JSON.stringify(row))
      this.temp = Object.assign({}, row1) // copy obj
      this.inquiryTeameruserName = this.temp.inquiryTeamerCode.userName

      this.temp.timestamp = new Date(this.temp.timestamp)
      this.faultTitle = this.temp.faultId.faultTitle
      this.dialogStatus = 'detail'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      // this.$router.push({ name: 'faultdetail', query: { faultId: row.faultId }})
    },
    getHtml() {
      this.faultContent = this.$refs.markdownEditor.getHtml()
      console.log(this.faultContent)
    },
    uploadfile(response, file, fileList) {
      this.file = response
    },
    handleChange() {},

    setSort() {
      const el = this.list[0]

      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)

          // for show the changes, you can delete in you code
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
        }
      })
    }
  }
}
</script>

<style>
.sortable-ghost{
  opacity: .8;
  color: #fff!important;
  background: #42b983!important;
}
</style>

<style scoped>
.icon-star{
  margin-right:2px;
}
.drag-handler{
  width: 20px;
  height: 20px;
  cursor: pointer;
}
.show-d{
  margin-top: 15px;
}
</style>
